using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Utility;
using Helper = PHSRAG.WebControls.Helper;

namespace PHSRAG.Insight21.Admin
{
    public partial class ResearchContactsManagement : CachePage
    {
        #region Constants

        private const string ChiefCodesKey = "chiefCodesKey_3CB37E01-DA3D-4057-9AF5-764ADE23BE6A";
        private const string CurrentPageIndexKey = "CurrentPageIndexKey_38FD02F7-34E9-4841-9841-A17D6CF142DF";
        private const string InstitutionsKey = "institutions_3CB37E01-DA3D-4057-9AF5-764ADE23BE6A";
        private const string PageResearchContactsKey = "pageResearchContactsKey_38FD02F7-34E9-4841-9841-A17D6CF142DF";
        private const string SponsorTypesKey = "sponsorTypesKey_3CB37E01-DA3D-4057-9AF5-764ADE23BE6A";

        #endregion

        #region Instance Variables (Private)

        private int selectedInsitutionId;
        private int selectedRoleId;

        #endregion

        #region Properties

        /// <summary>
        /// Get/Set the current page within the datagrid for display. This information persists across page loads.
        /// </summary>
        private int CurrentPageIndex
        {
            get
            {
                Hashtable h = PrevailingCachePolicy.GetCachedObject(PageCacheKey) as Hashtable;
                return (h == null || h[CurrentPageIndexKey] == null) ? 0 : (int) h[CurrentPageIndexKey];
            }
            set
            {
                Hashtable h = PrevailingCachePolicy.GetCachedObject(PageCacheKey) as Hashtable ?? new Hashtable();
                h[CurrentPageIndexKey] = value;
                dgResearchContacts.CurrentPageIndex = value;
                PrevailingCachePolicy.Cache(PageCacheKey, h);
            }
        }

        protected ListItemCollection Institutions
        {
            get
            {
                ListItemCollection institutions = (ListItemCollection) PrevailingCachePolicy.GetCachedObject(InstitutionsKey);

                if (institutions == null)
                {
                    institutions = new ListItemCollection();
                    institutions.Add(new ListItem(Helper.SelectPrompt, "0"));
                    foreach (DataRow dataRow in ResearchContacts.GetInstitutions(DataAccess.ConnectionString).Rows)
                    {
                        institutions.Add(new ListItem((string) dataRow["Name"], dataRow["Id"].ToString()));
                    }
                    PrevailingCachePolicy.Cache(InstitutionsKey, institutions);
                }

                return institutions;
            }
        }

        protected ListItemCollection ChiefCodes
        {
            get
            {
                ListItemCollection chiefCodes = new ListItemCollection();
                chiefCodes.Add(new ListItem(Helper.SelectPrompt, "0"));

                foreach (DataRow dataRow in ResearchContacts.GetChiefCodes(DataAccess.ConnectionString, selectedInsitutionId).Rows)
                {
                    chiefCodes.Add(new ListItem((string) dataRow["ChiefCode"], (string) dataRow["ChiefCode"]));
                }

                return chiefCodes;
            }
        }

        /// <summary>
        /// Get the list of Roles
        /// </summary>
        protected ListItemCollection Role
        {
            get
            {
                ListItemCollection role = new ListItemCollection();
                role.Add(new ListItem(Helper.SelectPrompt, "0"));
                foreach (DataRow dataRow in ResearchContacts.GetRoles(DataAccess.ConnectionString).Rows)
                {
                    role.Add(new ListItem((string) dataRow["Role"], dataRow["RoleId"].ToString()));
                }
                return role;
            }
        }

        /// <summary>
        /// Get the sponsor type based on Role
        /// </summary>
        protected ListItemCollection SponsorTypes
        {
            get
            {
                ListItemCollection sponsorTypes = new ListItemCollection();
                sponsorTypes.Add(new ListItem(Helper.SelectPrompt, "0"));
                foreach (DataRow dataRow in ResearchContacts.GetSponsorTypes(DataAccess.ConnectionString, selectedRoleId).Rows)
                {
                    sponsorTypes.Add(new ListItem((string) dataRow["Name"], dataRow["Id"].ToString()));
                }
                return sponsorTypes;
            }
        }

        #endregion

        #region Constructors

        public ResearchContactsManagement()
            : base("researchContactsMgmtCacheKey_3CB37E01-DA3D-4057-9AF5-764ADE23BE6A")
        {
        }

        #endregion

        #region Page Event Handlers

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                breadCrumb.Add("Research Contacts Management",
                    Settings.GetKeyValue("SubNavigation.Admin.ResearchContactsManagementURL", ""),
                    Settings.GetKeyValue("BreadCrumb.SummaryPageLevel", 1));

                //CR Scott
                // dgResearchContacts.PageSize = Utility.Settings.GetKeyValue("DataGrid.ItemsPerPage", 20);
                dgResearchContacts.PageSize = 50;
                annunciator.Message = string.Empty;

                if (!Page.IsPostBack)
                {
                    dgResearchContacts.EditItemIndex = -1;
                    CurrentPageIndex = 0;
                    LoadInstitution();
                    LoadResearchContacts(false);
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(annunciator, ex);
            }
        }

        #endregion

        #region Control Event Handlers

        /// <summary>
        /// Resets the subnavigation selected link(s) before the 
        /// header performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                adminSubNavigation.Reset();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(annunciator, ex);
            }
        }

        /// <summary>
        /// Adds new row to the grid
        /// </summary>
        /// <param name="sender">Control that raised the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnAddRow(object sender, EventArgs e)
        {
            try
            {
                LoadResearchContacts(true);
                add.Enabled = false;
                btnSearch.Enabled = false;
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(annunciator, ex);
            }
        }

        protected void onFilter(object sender, EventArgs e)
        {
            LoadResearchContacts(false);
        }


        protected void OnSelectContact(object sender, EventArgs e)
        {
            try
            {
                LoadResearchContacts(false);
                add.Enabled = false;
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(annunciator, ex);
            }
        }

        /// <summary>
        /// Occurs when the FirstPage hyperlink is clicked on the pager.
        /// The page's DataGrid is reloaded with the data belonging to the first page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnFirstPage(object sender, CommandEventArgs e)
        {
            try
            {
                CurrentPageIndex = 0;
                dgResearchContacts.EditItemIndex = -1;
                LoadResearchContacts(false);
                add.Enabled = true;
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(annunciator, ex);
            }
        }

        /// <summary>
        /// Occurs when the last page hyperlink is clicked on the pager.
        /// The page's DataGrid is reloaded with the data belonging to the last page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnLastPage(object sender, CommandEventArgs e)
        {
            try
            {
                CurrentPageIndex = topPager.PageCount - 1;
                dgResearchContacts.EditItemIndex = -1;
                LoadResearchContacts(false);
                add.Enabled = true;
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(annunciator, ex);
            }
        }

        /// <summary>
        /// Occurs when the NextPage hyperlink is clicked on the pager.
        /// The page's DataGrid is reloaded with the data belonging to the next page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnNextPage(object sender, CommandEventArgs e)
        {
            try
            {
                ++CurrentPageIndex;
                dgResearchContacts.EditItemIndex = -1;
                LoadResearchContacts(false);
                add.Enabled = true;
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(annunciator, ex);
            }
        }

        /// <summary>
        /// Occurs when the PreviousPage hyperlink is clicked on the pager.
        /// The page's DataGrid is reloaded with the data belonging to the previous page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnPreviousPage(object sender, CommandEventArgs e)
        {
            try
            {
                --CurrentPageIndex;
                dgResearchContacts.EditItemIndex = -1;
                LoadResearchContacts(false);
                add.Enabled = true;
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(annunciator, ex);
            }
        }

        protected void OnResearchContactsEditCommand(object source, DataGridCommandEventArgs e)
        {
            dgResearchContacts.EditItemIndex = e.Item.ItemIndex;
            LoadResearchContacts(false);
            btnSearch.Enabled = false;
        }

        protected void OnResearchContactsCancelCommand(object source, DataGridCommandEventArgs e)
        {
            dgResearchContacts.EditItemIndex = -1;
            LoadResearchContacts(false);
            add.Enabled = true;
            btnSearch.Enabled = true;
        }

        protected void OnItemCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
                {
                    if (e.CommandName == "Delete")
                    {
                        ResearchContact rc = new ResearchContact(PrevailingCachePolicy);
                        rc.Id = Convert.ToInt32(dgResearchContacts.DataKeys[e.Item.ItemIndex]);
                        rc.Delete(DataAccess.ConnectionString);
                        LoadResearchContacts(false);
                    }
                }
            }
            catch
            {
            }
        }

        protected void OnInstitutionSelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                DropDownList institution = (DropDownList) sender;

                int index = dgResearchContacts.EditItemIndex;
                DropDownList chiefCode = (DropDownList) dgResearchContacts.Items[index].FindControl("chiefCodeEdit");
                if (institution.SelectedIndex > 0)
                {
                    selectedInsitutionId = Convert.ToInt32(institution.SelectedValue);
                    chiefCode.DataSource = ChiefCodes;
                    chiefCode.DataTextField = "Text";
                    chiefCode.DataValueField = "Value";
                    chiefCode.DataBind();
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(annunciator, ex);
            }
        }

        /// <summary>
        /// Get sponsor types for selected role
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnRoleSelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                DropDownList role = (DropDownList) sender;

                int index = dgResearchContacts.EditItemIndex;
                DropDownList sponsor = (DropDownList) dgResearchContacts.Items[index].FindControl("admSponsorTypeEdit");

                if (role.SelectedIndex > 0)
                {
                    selectedRoleId = Convert.ToInt32(role.SelectedValue);
                    sponsor.DataSource = SponsorTypes;
                    sponsor.DataTextField = "Text";
                    sponsor.DataValueField = "Value";
                    sponsor.DataBind();
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(annunciator, ex);
            }
        }


        protected void OnDDInstitutionSelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ddInstitution.SelectedIndex > 0)
                {
                    selectedInsitutionId = Convert.ToInt32(ddInstitution.SelectedValue);
                    ddChiefCode.DataSource = ChiefCodes;
                    ddChiefCode.DataTextField = "Text";
                    ddChiefCode.DataValueField = "Value";
                    ddChiefCode.DataBind();
                }
                else
                {
                    ddChiefCode.Items.Clear();
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(annunciator, ex);
            }
        }

        protected void OnResearchContactsItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemIndex == dgResearchContacts.EditItemIndex)
            {
                DropDownList institution = (DropDownList) e.Item.FindControl("institutionEdit");
                DropDownList chiefCode = (DropDownList) e.Item.FindControl("chiefCodeEdit");
                DropDownList roles = (DropDownList) e.Item.FindControl("roleEdit");
                DropDownList admSponsorType = (DropDownList) e.Item.FindControl("admSponsorTypeEdit");
                HtmlInputHidden admPersonId = (HtmlInputHidden) e.Item.FindControl("admPersonId");
                TextBox contactPersonEdit = (TextBox) e.Item.FindControl("contactPersonEdit");
                ImageButton selectContact = (ImageButton) e.Item.FindControl("selectContact");
                DataRowView drv = e.Item.DataItem as DataRowView;

                if (drv != null)
                {
                    DataRow dr = drv.Row;
                    selectedInsitutionId = (int) dr[ResearchContact.ColumnInstitutionId];
                    institution.SelectedValue = selectedInsitutionId.ToString();
                    chiefCode.DataSource = ChiefCodes;
                    chiefCode.DataTextField = "Text";
                    chiefCode.DataValueField = "Value";
                    chiefCode.DataBind();

                    chiefCode.SelectedValue = dr[ResearchContact.ColumnChiefCode].ToString();

                    roles.DataSource = Role;
                    roles.DataTextField = "Text";
                    roles.DataValueField = "Value";
                    roles.DataBind();
                    roles.SelectedValue = dr[ResearchContact.ColumnRoleId].ToString();
                    //for sponsor

                    selectedRoleId = (int) dr[ResearchContact.ColumnRoleId];
                    admSponsorType.DataSource = SponsorTypes;
                    admSponsorType.DataTextField = "Text";
                    admSponsorType.DataValueField = "Value";
                    admSponsorType.DataBind();
                    admSponsorType.SelectedValue = dr[ResearchContact.ColumnAdmSponsorTypeId].ToString();

                    selectContact.Attributes.Add("onclick", "javascript:return SelectContact('" + admPersonId.ClientID + "', '" + contactPersonEdit.ClientID + "');");

                    LinkButton lnkDelete = (LinkButton) e.Item.FindControl("cmdDelete");

                    if (lnkDelete != null && lnkDelete.CommandName.Equals("Delete"))
                    {
                        lnkDelete.Visible = false;
                    }
                }
                else if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    LinkButton lnkDelete = (LinkButton) e.Item.FindControl("cmdDelete");

                    if (lnkDelete != null && lnkDelete.CommandName.Equals("Delete"))
                    {
                        lnkDelete.Visible = true;
                    }
                }
            }
        }

        protected void OnResearchContactsItemCreated(object source, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                LinkButton lnkDelete = (LinkButton) e.Item.FindControl("cmdDelete");
                lnkDelete.Attributes.Add("onclick", "return getconfirm();");
            }
        }

        protected void OnResearchContactsUpdateCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                Label fwkDomainOrganizationId = (Label) e.Item.FindControl("fwkDomainOrganizationId");
                DropDownList institution = (DropDownList) e.Item.FindControl("institutionEdit");
                DropDownList chiefCode = (DropDownList) e.Item.FindControl("chiefCodeEdit");
                DropDownList role = (DropDownList) e.Item.FindControl("roleEdit");
                DropDownList admSponsorType = (DropDownList) e.Item.FindControl("admSponsorTypeEdit");
                HtmlInputHidden admPersonId = (HtmlInputHidden) e.Item.FindControl("admPersonId");

                ResearchContact rc = new ResearchContact(PrevailingCachePolicy);
                rc.Id = Convert.ToInt32(dgResearchContacts.DataKeys[e.Item.ItemIndex]);
                rc.FwkDomainOrganizationId = Convert.ToInt32(fwkDomainOrganizationId.Text);
                rc.InstitutionId = Convert.ToInt32(institution.SelectedValue);
                rc.ChiefCode = chiefCode.SelectedValue;
                rc.RoleId = Convert.ToInt32(role.SelectedValue);
                rc.AdmSponsorTypeId = Convert.ToInt32(admSponsorType.SelectedValue);
                rc.AdmPersonId = Convert.ToInt32(admPersonId.Value);
                rc.Save(DataAccess.ConnectionString);

                dgResearchContacts.EditItemIndex = -1;
                LoadResearchContacts(false);
                add.Enabled = true;
                btnSearch.Enabled = true;
            }
            catch
            {
                annunciator.ForeColor = Color.Red;
                DisplayExceptionReport(annunciator, "Contact person for selected Institution and Role already exists");
            }
        }

        #endregion

        #region Private Methods

        private void LoadInstitution()
        {
            try
            {
                ddInstitution.DataSource = Institutions;
                ddInstitution.DataBind();
            }
            catch
            {
            }
        }

        private void LoadResearchContacts(bool showBlankRow)
        {
            ResearchContacts researchContacts;

            try
            {
                researchContacts = new ResearchContacts(PrevailingCachePolicy);

                //Check for search criteria
                if ((Convert.ToInt32(ddInstitution.SelectedValue) == 0) &&
                    (string.IsNullOrEmpty(ddChiefCode.SelectedValue) || Convert.ToInt32(ddChiefCode.SelectedValue) == 0) &&
                        string.IsNullOrEmpty(txtLastName.Text) &&
                            string.IsNullOrEmpty(txtFirstName.Text))
                {
                    researchContacts.Load(DataAccess.ConnectionString);
                }
                else
                {
                    researchContacts.LoadAdminContacts(DataAccess.ConnectionString,
                        Convert.ToInt32(ddInstitution.SelectedValue),
                        ddChiefCode.SelectedValue,
                        txtLastName.Text,
                        txtFirstName.Text);
                }

                DataTable source = researchContacts.GetDataContainer().Tables[0];

                if (showBlankRow)
                {
                    DataRow dr = source.NewRow();
                    dr[ResearchContact.ColumnId] = 0;
                    dr[ResearchContact.ColumnFwkDomainOrganizationId] = 0;
                    dr[ResearchContact.ColumnInstitutionId] = 0;
                    dr[ResearchContact.ColumnChiefCode] = "0";
                    dr[ResearchContact.ColumnAdmSponsorTypeId] = 0;
                    dr[ResearchContact.ColumnAdmPersonId] = 0;
                    dr[ResearchContact.ColumnRoleId] = 0;

                    source.Rows.Add(dr);
                }

                dgResearchContacts.VirtualItemCount = bottomPager.RecordCount =
                    topPager.RecordCount = source.Rows.Count;

                bottomPager.PageCount = topPager.PageCount = (topPager.RecordCount/dgResearchContacts.PageSize) +
                    (((topPager.RecordCount%dgResearchContacts.PageSize) == 0) ? 0 : 1);
                if (showBlankRow && topPager.PageCount > 0)
                {
                    //This check is required when the total no. of records lies on the page boundary. 
                    //If the number of records displayed on the last page is equal to the page size,
                    //and the user clicks on Add new row, then the blank row is displayed in the next page
                    CurrentPageIndex = topPager.PageCount - 1;
                }

                if (!showBlankRow && CurrentPageIndex >= topPager.PageCount && topPager.PageCount > 0)
                {
                    //This check is required when the total no. of records lies on the page boundary. 
                    //If the number of records displayed on the last page is equal to the page size,
                    //and the user clicks on Add new row, then the blank row is displayed in the next page
                    //If the user then clicks on cancel, then it should show the previous page
                    CurrentPageIndex = topPager.PageCount - 1;
                }
                bottomPager.CurrentPage = topPager.CurrentPage = CurrentPageIndex + 1;


                DataTable pageResearchContacts = GetPageContacts(source,
                    CurrentPageIndex*dgResearchContacts.PageSize, dgResearchContacts.PageSize);

                //check for emply resultset
                if (pageResearchContacts.Rows.Count > 0)
                {
                    dgResearchContacts.DataSource = pageResearchContacts;
                    dgResearchContacts.DataKeyField = "Id";
                }
                else
                {
                    gridContainer.Visible = false;
                    annunciator.Message = "No research contacts to display.";
                }

                if (showBlankRow)
                {
                    dgResearchContacts.EditItemIndex = pageResearchContacts.Rows.Count - 1;
                }

                dgResearchContacts.DataBind();

                if (pageResearchContacts.Rows.Count == 0)
                {
                    gridContainer.Visible = false;
                    annunciator.Message = "No research contacts to display.";
                }
                else
                {
                    //PrevailingCachePolicy.Cache(PageResearchContactsKey, pageResearchContacts);
                    gridContainer.Visible = true;
                    annunciator.Message = string.Empty;
                    recordCount.Text = topPager.RecordCount.ToString();
                }
                ManagePagination(source.Rows.Count);
            }
            catch
            {
            }
        }

        /// <summary>
        /// Gets Research Contacts bound by startIndex and count that need to be shown for the page
        /// </summary>
        /// <param name="source">List of all Research Contacts</param>
        /// <param name="startIndex">Starting index from where the page Research Contacts start</param>
        /// <param name="count">Number of Research Contacts to be shown on the page</param>
        /// <returns>List of Research Contacts to be shown on the page</returns>
        private DataTable GetPageContacts(DataTable source, int startIndex, int count)
        {
            DataTable pageContacts = source.Clone();
            int rowCount = source.Rows.Count;

            for (int i = startIndex, end = Math.Min(i + count, rowCount); i < end; ++i)
            {
                pageContacts.LoadDataRow(source.Rows[i].ItemArray, true);
            }

            return pageContacts;
        }

        /// <summary>
        /// Sets the pager control with corresponding values(Pagination management)
        /// </summary>
        private void ManagePagination(int totalCount)
        {
            int currentPageIndex = CurrentPageIndex;
            dgResearchContacts.CurrentPageIndex = currentPageIndex;

            int startIndex = currentPageIndex*dgResearchContacts.PageSize;
            bottomPager.FirstRecord = topPager.FirstRecord = startIndex + 1;

            bottomPager.LastRecord = topPager.LastRecord =
                Math.Min(startIndex + dgResearchContacts.PageSize, totalCount);
        }

        #endregion
    }
}